package level4.helpers
{
	/**
	 * 数组,助手
	 * */
	public class ArrayHelper
	{
		public function ArrayHelper()
		{
		}
		/**
		 * 数组中是否有item元素
		 * @param Array,原始数组
		 * @param *,某个元素
		 * */
		public static function hasSomething(arr:Array,item:*):Boolean{
			for(var i:int = 0;i<arr.length;i++){
				if(arr[i] == item)
					return true;
			}
			return false;
		}
		/**
		 * 获取 无重复元素的新数组
		 * @param Array,原始数组
		 * */
		public static function removeRepeat(arr:Array):Array{
			var newArr:Array = [];
			for(var i:int = 0;i<arr.length;i++){
				var item:* = arr[i];
				if(!hasSomething(newArr,item)){
					newArr.push(item);
				}
			}
			return newArr;
		}
		public static function bubbleSort(arr:Array):void{
			function bsort(arr:Array):void{
				var len:int = arr.length;
				var exchange:Number = 0;
				
				for(var i:int = 0;i<len;i++){
					for(var j:int=0;j<len;j++){
						if(j<len){
							if(arr[j]>arr[j+1]){
								exchange = arr[j];
								arr[j] = arr[j+1];
								arr[j+1] = exchange;
							}
						}
					}
				}
				
			}
		}
		/**
		 * 将大数组,分割为多个小数组,完毕后大数组被销毁
		 * @param largeList : Array ,大数组
		 * @perGroupItemCount : int , 每个小数组中的元素的个数
		 * @return Array : 包含多个小数组的大数组.
		 * 
		 * */
		public static function splitLargeList(largeList:Array,perGroupItemCount:int):Array{
			var groupCount:int = Math.ceil(largeList.length/perGroupItemCount);
			var group:Array = null;
			var item:* = null;
			var allGroup:Array = [];
			for(var i:int = 0;i<groupCount;i++){
				group = [];
				allGroup.push(group);
				for(var j:int=0;j < perGroupItemCount;j++){
//					var index:int = i*groupNum + j;
//					group.push(worldList[index]);
					item = largeList.shift();
					if(item){
						group.push(item);
					}else{
						break;
					}
				}
			}
			return allGroup;
		}
		
		public static function binarySearch(arr:Array,item:int):int{
			var low:int = 0;
			var high:int = arr.length-1;
			
			while(low <= high){
				var mid:int = (low + high) >> 1;
				var midValue:int = arr[mid];
				if(midValue < item){
					low = mid + 1;
				}else if(midValue > item){
					high = mid -1;
				}else{
					return mid;
				}
			}
			return -1;
		}
		
		public static function recursiveBinarySearch(arr:Array,low:int,high:int,item:int):int{
			var mid:int = (low + high) >> 1;
			var midValue:int = arr[mid];
			if(midValue < item && mid + 1 <= high){
				return recursiveBinarySearch(arr,mid+1,high,item);
			}else if(midValue > item && mid-1 >= low){
				return recursiveBinarySearch(arr,low,mid-1,item);
			}else if(midValue == item){
				return mid;
			}
			return -1;
		}
		
	}
}